package com.util;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

//拦截器
public class MyInterceptor1 implements HandlerInterceptor {

    //预处理方法，返回值boolean true代表放行，false拦截返回；
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("预处理");
        //得到所有参数的key；
        Enumeration<String> keys = request.getParameterNames();
        //遍历keys,要求必须有bookId才能进；
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            if ("bookId".equals(key)) {
                return true;
            }
        }
        //设置400错误
        response.setStatus(400);
        return false;
    }

    //后处理方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //已经设置在tips.jsp中显示；
        modelAndView.addObject("tips","这是通过拦截器的后处理添加的数据。");
        System.out.println("后处理");
    }

}
